﻿using System;
using NetTopologySuite.Utilities;

namespace NetTopologySuite.Precision
{
	public class CommonBits
	{
		public static long SignExpBits(long num)
		{
			return num >> 52;
		}

		public static int NumCommonMostSigMantissaBits(long num1, long num2)
		{
			int num3 = 0;
			for (int i = 52; i >= 0; i--)
			{
				if (CommonBits.GetBit(num1, i) != CommonBits.GetBit(num2, i))
				{
					return num3;
				}
				num3++;
			}
			return 52;
		}

		public static long ZeroLowerBits(long bits, int nBits)
		{
			long num = ~((1L << nBits) - 1L);
			return bits & num;
		}

		public static int GetBit(long bits, int i)
		{
			long num = 1L << i;
			if ((bits & num) == 0L)
			{
				return 0;
			}
			return 1;
		}

		public void Add(double num)
		{
			long num2 = System.BitConverter.DoubleToInt64Bits(num);
			if (this._isFirst)
			{
				this._commonBits = num2;
				this._commonSignExp = CommonBits.SignExpBits(this._commonBits);
				this._isFirst = false;
				return;
			}
			if (CommonBits.SignExpBits(num2) != this._commonSignExp)
			{
				this._commonBits = 0L;
				return;
			}
			this._commonMantissaBitsCount = CommonBits.NumCommonMostSigMantissaBits(this._commonBits, num2);
			this._commonBits = CommonBits.ZeroLowerBits(this._commonBits, 64 - (12 + this._commonMantissaBitsCount));
		}

		public double Common
		{
			get
			{
				return System.BitConverter.Int64BitsToDouble(this._commonBits);
			}
		}

		public string ToString(long bits)
		{
			double num = System.BitConverter.Int64BitsToDouble(bits);
			string str = HexConverter.ConvertAny2Any(bits.ToString(), 10, 2);
			string text = "0000000000000000000000000000000000000000000000000000000000000000" + str;
			string text2 = text.Substring(text.Length - 64);
			return string.Concat(new object[]
			{
				text2.Substring(0, 1),
				"  ",
				text2.Substring(1, 12),
				"(exp) ",
				text2.Substring(12),
				" [ ",
				num,
				" ]"
			});
		}

		private bool _isFirst = true;

		private int _commonMantissaBitsCount = 53;

		private long _commonBits;

		private long _commonSignExp;
	}
}
